package com.wind.cloud.zero.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.wind.cloud.zero.domain.User;
import com.wind.cloud.zero.mapper.UserMapper;

@RestController
@RequestMapping("user")
public class UserController
{
    @Autowired
    private UserMapper      userMapper;

    @Autowired
    private DiscoveryClient client;

    @GetMapping("list")
    public List<User> list()
    {
        return userMapper.findByAll(null);
    }

    @GetMapping("get/{id}")
    @HystrixCommand(fallbackMethod = "processHystrix_Get")
    public User get(@PathVariable Integer id)
    {
        User user = userMapper.selectByPrimaryKey(id);
        if (null == user)
        {
            throw new RuntimeException("找不到用户");
        }
        return user;
    }

    @GetMapping("del/{id}")
    public boolean del(@PathVariable Integer id)
    {
        return userMapper.deleteByPrimaryKey(id) > 0;
    }

    @PostMapping("add")
    public boolean add(@RequestBody User user)
    {
        return userMapper.insert(user) > 0;
    }

    @RequestMapping(value = "discovery", method = RequestMethod.GET)
    public Object discovery()
    {
        List<String> list = client.getServices();
        System.out.println("**********" + list);
        List<ServiceInstance> srvList = client.getInstances("cloud-zero-USER");
        for (ServiceInstance element : srvList)
        {
            System.out.println(element.getServiceId() + "\t" + element.getHost() + "\t" + element.getPort() + "\t"
                    + element.getUri());
        }
        return this.client;
    }

    public User processHystrix_Get(@PathVariable Integer id)
    {
        return new User().setId(id).setName("该ID：" + id + " 没有对应的信息,null").setAge(0);
    }
}
